<template>
  <div class="user-management">
    <!-- 添加贫困户按钮和搜索区域 -->
    <div class="search-area">
      <el-button type="primary" @click="showAddDialog">+ 添加贫困户</el-button>
      <div class="search-inputs">
        <el-input v-model="searchParams.belongArea" placeholder="请输入贫困户所属地区" clearable
          style="width: 200px; margin-right: 10px;margin-left: 30px;" />
        <el-input v-model="searchParams.headName" placeholder="请输入贫困户姓名" clearable
          style="width: 200px; margin-right: 10px;" />
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </div>
    </div>

    <!-- 贫困户表格 -->
    <div class="table-container">
      <el-table :data="pagedUsers" border style="width: 100%; margin-top: 20px;">
        <el-table-column prop="familyNumber" label="贫困户编号" width="100" />
        <el-table-column prop="headName" label="户主姓名" width="100" />
        <el-table-column prop="belongArea" label="所属乡村" width="110" />
        <el-table-column prop="gender" label="性别" width="50">
          <template #default="{ row }">
            {{ row.gender === 'M' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="riskType" label="风险类型" width="200" />
        <el-table-column prop="riskRemark" label="风险备注" width="180" />
        <el-table-column prop="createTime" label="录入时间" width="100">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" icon="el-icon-edit" @click="showEditDialog(row)">修改
              </el-button>
              <el-button type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination v-model="currentPage" :page-size="pageSize" layout="prev, pager, next" :total="totalUsers">
      </el-pagination>
    </div>

    <!-- 添加/编辑贫困户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" :before-close="handleCloseDialog">
      <el-form :model="userForm" label-width="120px">
        <el-form-item label="贫困户编号" required>
          <el-input v-model="userForm.familyNumber" :disabled="isEditing" />
        </el-form-item>
        <el-form-item label="贫困户姓名" required>
          <el-input v-model="userForm.headName" />
        </el-form-item>
        <el-form-item label="性别" required>
          <el-radio-group v-model="userForm.gender">
            <el-radio label="M">男</el-radio>
            <el-radio label="F">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属乡村" required>
          <el-input v-model="userForm.belongArea" />
        </el-form-item>
        <el-form-item label="风险类型" required>
          <el-input v-model="userForm.riskType" />
        </el-form-item>
        <el-form-item label="风险备注" required>
          <el-input v-model="userForm.riskRemark" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="display: flex; justify-content: center; gap: 10px;">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPoorFamily, updatePoorFamily, addPoorFamily, deletePoorFamily } from '@/api/vselete'
//分页参数
const currentPage = ref(1)
const pageSize = ref(10)
//表格需要展示的数据对象数组
const pagedUsers = ref([])
// 搜索参数
const searchParams = reactive({
  //familyId: '',
  belongArea: '',
  headName: '',
  currentPage: currentPage.value,
  pageSize: pageSize.value
})

//分页的总记录数
const totalUsers = ref(0)
//查询当前表格中的数据
const queryUser = () => {
  getPoorFamily(searchParams).then((res) => {
    if (res.code == 2000) {
      pagedUsers.value = res.data
      totalUsers.value = res.total
    } else {
      pagedUsers.value = []
      totalUsers.value = 0
    }
  })
}
queryUser()

// 对话框相关状态
const dialogVisible = ref(false)
const isEditing = ref(false)
//const currentUserId = ref('')
const dialogTitle = computed(() => isEditing.value ? '修改贫困户信息' : '添加贫困户')

// 贫困户表单
const userForm = reactive({
  familyid: '',
  familyNumber: '',
  headName: '',
  gender: 'M',
  belongArea: '',
  riskType: '',
  riskRemark: '',
  createTime: '',
})

// 计算总贫困户数


// 计算当前页显示的贫困户
/*const pagedUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})*/

// 计算总条目数
//const totalItems = computed(() => filteredUsers.value.length)

// 显示添加对话框
const showAddDialog = () => {
  isEditing.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  isEditing.value = true
  //currentUserId.value = row.userId
  Object.assign(userForm, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(userForm, {
    familyNumber: '',
    headName: '',
    gender: 'M',
    userVillage: '',
    riskType: '',
    riskRemark: ''
  })
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
}

// 确认添加/编辑
const handleConfirm = () => {
  // 验证必填字段
  if (!userForm.familyNumber || !userForm.headName || !userForm.belongArea || !userForm.riskRemark) {
    ElMessage.warning('请填写完整信息')
    return
  }

  if (isEditing.value) {
    // 更新贫困户
    //const index = users.value.findIndex(user => user.userId === currentUserId.value)
    if (isEditing.value) {
      updatePoorFamily(userForm).then(res => {
        if (res.code == 2000) {
          ElMessage.success('修改成功')
          handleSearch()
        }
      })
    }
  } else {
    addPoorFamily(userForm).then(res => {
      if (res.code == 2000) {
        ElMessage.success('添加成功')
        handleSearch()
      }
    })
  }
  dialogVisible.value = false
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('是否确认删除该贫困户?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deletePoorFamily(row.familyId).then(res => {
      ElMessage.success('删除成功')
      handleSearch() // 重新筛选数据
    })
  })
}

// 处理搜索
const handleSearch = () => {
  queryUser()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  queryUser()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  queryUser()
}

/*return {
  // 数据绑定
  users,
  searchParams,
  pagedUsers,
  totalUsers,
  currentPage,
  pageSize,
  dialogVisible,
  isEditing,
  dialogTitle,
  userForm,
  
  // 对话框操作
  showAddDialog,
  showEditDialog,
  handleCloseDialog,
  resetForm,
  
  // 数据操作
  handleConfirm,
  handleDelete,
  handleSearch,
  
  // 分页操作
  handleSizeChange,
  handleCurrentChange,
  
  // 计算属性
  totalItems
}*/
</script>

<style scoped>
.el-table__header .cell {
  text-align: center !important;
}

.user-management {
  padding: 20px;
  min-height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.search-area {
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
  max-width: 1100px;
}

.search-inputs {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 确保按钮文字居中 */
.el-button {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

/* 让表格中所有单元格的文字居中 */
.el-table .cell {
  text-align: center !important;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  align-items: center;
  text-align: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  max-width: 1100px;
}

.table-container {
  width: 100%;
  max-width: 1100px;
  display: flex;
  justify-content: center;
}

.el-table {
  min-width: 100%;
  table-layout: auto;
}

.el-dialog {
  max-width: 90%;
  margin: 0 auto;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .search-inputs {
    flex-direction: column;
    align-items: flex-start;
  }

  .el-table {
    font-size: 14px;
  }
}
</style>